package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.model.result.StarInfoResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.IPushExtHandleService;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * apib 撞库返回授权地址
 * 通知进件
 *
 */
@Service
public class WeiHaoYongApiBMaskPushApiService implements IPushApiService, IPushApi2Service,IPushExtHandleService {

    private static final Logger log = LogFactory.getPushLog();

    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Autowired
    IApplicationInfoService applicationInfoService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("orderNo", orderNo);
        paramMap.put("mobileMd5", memberSourceInfo.getMobileMd5());
        paramMap.put("mobileMask", memberSourceInfo.getMobile().substring(0,8));
        paramMap.put("realname", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", 1);
        }else {
            paramMap.put("sex", 2);
        }
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("province",memberSourceInfo.getProvince());
        paramMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("loanAmount",memberSourceInfo.getLoanAmount());
        paramMap.put("huabei",memberSourceInfo.getHuabei());
        paramMap.put("shebao",memberSourceInfo.getShebao());
        paramMap.put("baitiao",memberSourceInfo.getBaitiao());
        paramMap.put("yuqi",memberSourceInfo.getYuqi());
        paramMap.put("house",memberSourceInfo.getHouse());
        paramMap.put("loanTime",memberSourceInfo.getLoanTime());
        paramMap.put("baoxian",memberSourceInfo.getBaoxian());
        paramMap.put("xueli",memberSourceInfo.getXueli());
        paramMap.put("car",memberSourceInfo.getCar());
        paramMap.put("shouru",memberSourceInfo.getShouru());
        paramMap.put("gongzuo",memberSourceInfo.getGongzuo());
        paramMap.put("yongtu",memberSourceInfo.getYongtu());
        if (StringUtils.isEmpty(memberSourceInfo.getWeili())){
            paramMap.put("weili", BaseTypeInfoEnum.WeiLi.wl001.getValue());
        }else {
            paramMap.put("weili",memberSourceInfo.getWeili());
        }
        if (StringUtils.isEmpty(memberSourceInfo.getXinyongka())){
            paramMap.put("xinyongka",BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            paramMap.put("xinyongka",memberSourceInfo.getXinyongka());
        }

        paramMap.put("gjj",memberSourceInfo.getGjj());
        paramMap.put("zhima",memberSourceInfo.getZhima());
        paramMap.put("ip", memberSourceInfo.getReqIp());

        //加密
        String encrypt =  SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(paramMap));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("requestNo", UUID.randomUUID().toString());
        bizMap.put("appCode",pushApiKeyParam.getApiCode());
        bizMap.put("tranData",encrypt);

        String  checkUrl = pushApiKeyParam.getCheckUrl();

        log.info("【半流程导量】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), checkUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(checkUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【半流程导量】撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("respCode");
        String respMsg = resultObject.getString("respMsg");

        pushApiResult.setCode(respCode);
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(respCode, "200")) {

            JSONObject respData = resultObject.getJSONObject("respData");

            String status = respData.getString("status");
            String message = respData.getString("message");
            String outOrderNo = respData.getString("outOrderNo");
            JSONArray md5List = respData.getJSONArray("md5List");
            String mobileMd5 = memberSourceInfo.getMobileMd5();
            if (MobileMd5IsInListUtils.isMobileMd5InList(md5List, mobileMd5)) {
                // 存在
                pushApiResult.setCode(respCode + "|" + "500");
                pushApiResult.setMessage(respMsg + "|" + mobileMd5 + "号码已存在");
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }

            pushApiResult.setCode(respCode + "|" + status);
            pushApiResult.setMessage(respMsg + "|" + message);
            if (StrUtil.equals(status, "000")){
                pushApiResult.setPushSuccess(true);

                pushApiResult.setOutOrderNo(outOrderNo);
                extJson.put("outOrderNo",outOrderNo);

                //进行分润操作
                String priceType = pushApiKeyParam.getPriceType();
                BigDecimal typeRate = pushApiKeyParam.getTypeRate();
                if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                    BigDecimal price = respData.getBigDecimal("price");//下游返回分润前价格
                    if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                        pushApiResult.setPushSuccess(false);
                        return pushApiResult;
                    }
                    BigDecimal priceRight = price.divide(typeRate,2, RoundingMode.HALF_UP);//分润后价格
                    pushApiResult.setPrice(priceRight);
                    pushApiResult.setPriceRight(price);
                }
            }
            return pushApiResult;
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String outOrderNo = extJson.getString("outOrderNo");

        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("orderNo", orderNo);
        paramMap.put("outOrderNo", outOrderNo);

        paramMap.put("mobile", memberSourceInfo.getMobile());
        paramMap.put("realname", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", 1);
        }else {
            paramMap.put("sex", 2);
        }
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("province",memberSourceInfo.getProvince());
        paramMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("loanAmount",memberSourceInfo.getLoanAmount());
        paramMap.put("huabei",memberSourceInfo.getHuabei());
        paramMap.put("shebao",memberSourceInfo.getShebao());
        paramMap.put("baitiao",memberSourceInfo.getBaitiao());
        paramMap.put("yuqi",memberSourceInfo.getYuqi());
        paramMap.put("house",memberSourceInfo.getHouse());
        paramMap.put("loanTime",memberSourceInfo.getLoanTime());
        paramMap.put("baoxian",memberSourceInfo.getBaoxian());
        paramMap.put("xueli",memberSourceInfo.getXueli());
        paramMap.put("car",memberSourceInfo.getCar());
        paramMap.put("shouru",memberSourceInfo.getShouru());
        paramMap.put("gongzuo",memberSourceInfo.getGongzuo());
        paramMap.put("yongtu",memberSourceInfo.getYongtu());
        if (StringUtils.isEmpty(memberSourceInfo.getWeili())){
            paramMap.put("weili", BaseTypeInfoEnum.WeiLi.wl001.getValue());
        }else {
            paramMap.put("weili",memberSourceInfo.getWeili());
        }
        if (StringUtils.isEmpty(memberSourceInfo.getXinyongka())){
            paramMap.put("xinyongka",BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            paramMap.put("xinyongka",memberSourceInfo.getXinyongka());
        }

        paramMap.put("gjj",memberSourceInfo.getGjj());
        paramMap.put("zhima",memberSourceInfo.getZhima());
        paramMap.put("ip", memberSourceInfo.getReqIp());
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String authUrl = StrUtil.format("{}/page/protocolHaoYong/{}.html", appInfoByAppCode.getApiUrl(), memberSourceInfo.getUid());
        paramMap.put("authUrl", authUrl);

        //加密
        String encrypt =  SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(paramMap));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("requestNo", UUID.randomUUID().toString());
        bizMap.put("appCode",pushApiKeyParam.getApiCode());
        bizMap.put("tranData",encrypt);

        String  registerUrl = pushApiKeyParam.getRegisterUrl();

        log.info("【半流程导量】 进件开始【infoId】{}【infoName】{}【registerUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), registerUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(registerUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【半流程导量】进件结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("respCode");
        String respMsg = resultObject.getString("respMsg");

        pushApiResult.setCode(respCode);
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(respCode, "200")) {

            JSONObject respData = resultObject.getJSONObject("respData");

            String status = respData.getString("status");
            String message = respData.getString("message");
            String approveUrl = respData.getString("approveUrl");

            pushApiResult.setCode(respCode + "|" + status);
            pushApiResult.setMessage(respMsg + "|" + message);
            if (StrUtil.equals(status, "000")){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setOutOrderNo(outOrderNo);
                pushApiResult.setApproveUrl(approveUrl);
            }
            return pushApiResult;
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        throw new RuntimeException();
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        // TODO: 2024/9/5 实现查询方法


        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());

        JSONObject jsonObject = JSON.parseObject(paramContent);

        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }

        String orderNo = jsonObject.getString("orderNo");
        noticeParamDTO.setOrderNo(orderNo);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOrderNoAndInfoIdLock(orderNo, Integer.valueOf(infoId));

        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }

        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;


    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", "000");
        jsonObject.put("message", "回调成功");
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    @Override
    public StarInfoResult handleStarInfo(MerchantBaseInfo merchantBaseInfo, Map<String, String[]> parameterMap, String paramContent) throws Exception {
        StarInfoResult starInfoResult = new StarInfoResult();
        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);

        if (ObjectUtil.isEmpty(jsonObjectParamContent)) {
            return starInfoResult;
        }

        String mobileMd5 = jsonObjectParamContent.getString("mobileMd5");
        Integer startLevel = jsonObjectParamContent.getInteger("startLevel");
        starInfoResult.setMobileMd5(mobileMd5);
        starInfoResult.setStarLevel(startLevel);
        return starInfoResult;
    }

    @Override
    public PushApiResult checkUserCode(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String mobileMask = memberSourceInfo.getMobileMask();
        if (StringUtils.isEmpty(mobileMask)){
            pushApiResult.setCode("301");
            pushApiResult.setMessage("掩码不存在,不进行撞库");
            return pushApiResult;
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("orderNo", orderNo);

        paramMap.put("mobileMask", mobileMask);
        paramMap.put("realname", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", 1);
        }else {
            paramMap.put("sex", 2);
        }
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("province",memberSourceInfo.getProvince());
        paramMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("loanAmount",memberSourceInfo.getLoanAmount());
        paramMap.put("huabei",memberSourceInfo.getHuabei());
        paramMap.put("shebao",memberSourceInfo.getShebao());
        paramMap.put("baitiao",memberSourceInfo.getBaitiao());
        paramMap.put("yuqi",memberSourceInfo.getYuqi());
        paramMap.put("house",memberSourceInfo.getHouse());
        paramMap.put("loanTime",memberSourceInfo.getLoanTime());
        paramMap.put("baoxian",memberSourceInfo.getBaoxian());
        paramMap.put("xueli",memberSourceInfo.getXueli());
        paramMap.put("car",memberSourceInfo.getCar());
        paramMap.put("shouru",memberSourceInfo.getShouru());
        paramMap.put("gongzuo",memberSourceInfo.getGongzuo());
        paramMap.put("yongtu",memberSourceInfo.getYongtu());
        if (StringUtils.isEmpty(memberSourceInfo.getWeili())){
            paramMap.put("weili", BaseTypeInfoEnum.WeiLi.wl001.getValue());
        }else {
            paramMap.put("weili",memberSourceInfo.getWeili());
        }
        if (StringUtils.isEmpty(memberSourceInfo.getXinyongka())){
            paramMap.put("xinyongka",BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            paramMap.put("xinyongka",memberSourceInfo.getXinyongka());
        }

        paramMap.put("gjj",memberSourceInfo.getGjj());
        paramMap.put("zhima",memberSourceInfo.getZhima());
        paramMap.put("ip", memberSourceInfo.getReqIp());

        //加密
        String encrypt =  SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(paramMap));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("requestNo", UUID.randomUUID().toString());
        bizMap.put("appCode",pushApiKeyParam.getApiCode());
        bizMap.put("tranData",encrypt);

        String  checkUrl = pushApiKeyParam.getCheckUrl();

        log.info("【半流程导量】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), checkUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(checkUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【半流程导量】撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("respCode");
        String respMsg = resultObject.getString("respMsg");

        pushApiResult.setCode(respCode);
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(respCode, "200")) {

            JSONObject respData = resultObject.getJSONObject("respData");

            String status = respData.getString("status");
            String message = respData.getString("message");
            String outOrderNo = respData.getString("outOrderNo");

            pushApiResult.setCode(respCode + "|" + status);
            pushApiResult.setMessage(respMsg + "|" + message);
            if (StrUtil.equals(status, "000")){
                pushApiResult.setPushSuccess(true);

                pushApiResult.setOutOrderNo(outOrderNo);
                extJson.put("outOrderNo",outOrderNo);

                //进行分润操作
                String priceType = pushApiKeyParam.getPriceType();
                BigDecimal typeRate = pushApiKeyParam.getTypeRate();
                if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                    BigDecimal price = respData.getBigDecimal("price");//下游返回分润前价格
                    if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                        pushApiResult.setPushSuccess(false);
                        return pushApiResult;
                    }
                    BigDecimal priceRight = typeRate.multiply(price);//分润后价格
                    pushApiResult.setPrice(price);
                    pushApiResult.setPriceRight(priceRight);
                }
            }
            return pushApiResult;
        }

        return pushApiResult;
    }
}
